package com.noodles.mall.web;

import com.fasterxml.jackson.annotation.JsonInclude;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;

import java.io.Serializable;

@Data
@JsonInclude(JsonInclude.Include.NON_NULL)
@NoArgsConstructor
public class JsonResult<T> implements Serializable {

    // 状态码，例如：200
    private Integer state;
    // 消息，例如："登录失败，用户名不存在"
    @JsonInclude(JsonInclude.Include.NON_NULL)
    private String msg;
    // 数据
    @JsonInclude(JsonInclude.Include.NON_NULL)
    private T data;

    public JsonResult(State state, String msg, T data) {
        this.state = state.getValue();
        this.msg = msg;
        this.data = data;
    }

    /**
     * @return 成功状态码
     */
    public static JsonResult<Void> success() {
        return new JsonResult<Void>(State.OK,null,null);
    }

    /**
     * @return 成功状态码, 数据
     */
    public static <T> JsonResult<T> success(T data) {
        return new JsonResult<T>(State.OK,null,data);
    }

    /**
     * @return 成功状态码, 消息, 数据
     */
    public static <T> JsonResult<T> success(String msg,T data) {
        return new JsonResult<T>(State.OK,msg,data);
    }

    /**
     * @return 某个失败状态码, 消息
     */
    public static JsonResult<Void> error(State state, String msg) {
        return new JsonResult<Void>(state,msg,null);
    }

    /**
     * @return 某个失败状态码
     */
    public static JsonResult<Void> error(State state) {
        return new JsonResult<Void>(state, null,null);
    }

    /**
     * @return 某个失败状态码, 消息
     */
    public  static <T> JsonResult<T> error(State state,String msg, T data) {
        return new JsonResult<T>(state, msg,data);
    }
}
